﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace ModelHasher.Framework
{
    public class ModelHash
    {
        private const int legacyHashLenght = 8;
        private const int shortHashLenght = 10;

        public string Name { get; set; } = null;

        private string hash = null;
        public string Hash
        {
            get => hash;
            set => UpdateHash(value);
        }

        private string legacyHash = null;
        [XmlIgnore]
        public string LegacyHash
        {
            get
            {
                if (legacyHash == null)
                {
                    legacyHash = Hash.Substring(0, legacyHashLenght);
                }
                return legacyHash;
            }
        }

        private string shortHash = null;
        [XmlIgnore]
        public string ShortHash
        {
            get
            {
                if (shortHash == null)
                {
                    shortHash = Hash.Substring(0, shortHashLenght);
                }
                return shortHash;
            }
        }

        protected ModelHash() { }

        public ModelHash(string name, string hash)
        {
            Name = name;
            Hash = hash.ToLower(CultureInfo.InvariantCulture);
            shortHash = Hash.Substring(0, shortHashLenght);
            legacyHash = Hash.Substring(0, legacyHashLenght);
        }

        public void UpdateHash(string newHash)
        {
            if (!string.Equals(newHash, Hash))
            {
                hash = newHash.ToLower(CultureInfo.InvariantCulture);
                shortHash = null;
                legacyHash = null;
            }
        }
    }
}
